const UserService = require('./user');
const ContractService = require('./contract');
const WorkerService = require('./worker');
const WorkerSignRecordService = require('./workerSignRecordService');
const TenantService = require('./tenant');
const TenantSignRecordService = require('./tenantSignRecordService');
const OrganizationService = require('./organization');
const NoticeService = require('./notice');
const { logger } = require('../utils');

class CallbackService {
  constructor() {
    if (process.env.REDIS_DB_ENABLE) {
      this.userService = new UserService();
      this.contractService = new ContractService();
      this.workerService = new WorkerService();
      this.tenantService = new TenantService();
      this.workerSignRecordService = new WorkerSignRecordService();
      this.tenantSignRecordService = new TenantSignRecordService();
      this.organizationService = new OrganizationService();
      this.noticeService = new NoticeService();
    }
  }

  async orgOpenTsignBiz(data) {
    if (data?.ProxyAppId) {
      const targetUser = this.userService.find(data.ProxyOperatorOpenId);
      if (targetUser) {
        this.userService.update(data.ProxyOperatorOpenId, {
          userName: data.LegalName,
        });
      } else {
        this.userService.create({
          id: data.ProxyOperatorOpenId,
          openId: data.ProxyOperatorOpenId,
          userId: data.ProxyOperatorOpenId,
          userName: data.LegalName,
        });
      }
      const targetOrg = this.organizationService.find(data.ProxyOrganizationOpenId);
      if (targetOrg) {
        this.organizationService.update(data.ProxyOrganizationOpenId, {
          proxyAppId: data?.ProxyAppId,
        });
      } else {
        this.organizationService.create({
          id: data.ProxyOrganizationOpenId,
          proxyAppId: data.ProxyAppId,
          organizationName: data.OrganizationName,
          organizationOpenId: data.ProxyOrganizationOpenId,
        });
      }
    }
  }

  async updateSignStatusChange(data) {
    if (data.FlowId) {
      await this.contractService.updateCallbackChangeStatus(data.FlowId, data);

      try {
        const workerSign = await this.workerSignRecordService.first({
          contractId: data.FlowId,
        });
        const NeedUpdateStatus = ['ALL', 'CANCEL', 'REJECT', 'INIT', 'DEADLINE', 'EXCEPTION'];
        const getNewStatus = (status, initialStatus) => {
          if (['CANCEL', 'REJECT', 'DEADLINE', 'EXCEPTION'].includes(status)) return initialStatus;
          if (['PART'].includes(status)) return 'INIT';
          return status;
        };
        if (workerSign) {
          // 工人合同
          if (NeedUpdateStatus.includes(data.FlowStatus)) {
            // 以上状态才需要变更关联表状态
            const newWorkerData = {};
            if (workerSign.type === 'safe-proposal') { // 签署类型是安全承诺书
              newWorkerData.proposalStatus = getNewStatus(data.FlowStatus, '');// 更新工人安全承诺书状态
            } else {
              newWorkerData.status = getNewStatus(data.FlowStatus, '');// 更新工人状态
            }
            await this.workerService.update(workerSign.workerId, newWorkerData); // 更新员工状态
          }
          await this.workerSignRecordService.update(workerSign.id, {
            status: data.FlowStatus,
          }); // 更新工人签署记录状态
          try {
            if (data.FlowStatus === 'ALL') {
              const workerItem = (await this.workerService.find(workerSign.workerId)) || {};
              this.noticeService.addNotice({
                message: `【劳务合同】${workerItem.name} ${workerItem.mobile} -- 已签署`,
                organizationId: data.ProxyOrganizationOpenId,
              });
            }
          } catch (err) {
            logger.error({
              category: 'notice',
              err,
            });
            console.log(err, 'notice worker error');
          }
        }
        // 用工合同
        const tenantSign = await this.tenantService.first({
          flowIds: data.FlowId,
        });
        if (tenantSign) {
          // 更新用工单位签署状态
          await this.tenantService.update(tenantSign.id, {
            latestFlowStatus: getNewStatus(data.FlowStatus, 'UNDISTURBED'),
          });
          // 更新企业签署记录状态
          await this.tenantSignRecordService.update(tenantSign.id, {
            tenantStatus: getNewStatus(data.FlowStatus, 'UNDISTURBED'),
          });

          try {
            if (data.FlowStatus === 'ALL') {
              this.noticeService.addNotice({
                message: `【劳务派遣协议】${tenantSign.name} -- 已达成协议`,
                organizationId: data.ProxyOrganizationOpenId,
              });
            }
          } catch (err) {
            logger.error({
              category: 'notice',
              err,
            });
            console.log(err, 'notice organization error');
          }
        }
        logger.info({
          action: 'updateSignStatusChange',
          data: {
            tenant: tenantSign,
            tenantStatus: getNewStatus(data.FlowStatus, 'UNDISTURBED'),
          },
        });
        // else { // 企业合同
        //   const tenantSign = await this.tenantSignRecordService.findBy({
        //     contractId: data.FlowId,
        //   });
        //   if (tenantSign) {
        //     await this.tenantService.update({
        //       id: tenantSign.tenantId,
        //       latestFlowStatus: data.FlowStatus,
        //     });// 更新用工单位签署状态
        //     if (NeedUpdateStatus.includes(data.FlowStatus)) { // 以上状态才需要变更关联表状态
        //       await this.tenantService.update({
        //         id: tenantSign.tenantId,
        //         latestFlowStatus: getNewStatus(data.FlowStatus, 'UNDISTURBED'),
        //       });// 更新用工单位签署状态
        //     }
        //     this.tenantSignRecordService.update({
        //       id: tenantSign.id,
        //       tenantStatus: data.FlowStatus,
        //     });// 更新企业签署记录状态
        //   }
        // }
        return true;
      } catch (error) {
        return false;
      }
    }
  }
  // 经办人加入企业
  async insertChannelOperator(data) {
    const targetUser = this.userService.find(data.ProxyOperatorOpenId);
    if (targetUser) {
      this.userService.update(data.ProxyOperatorOpenId, {
        status: 'VERIFIED',
      });
    } else {
      logger.error({
        type: 'callback',
        msg: '用户不存在',
      });
    }
  }
}

module.exports = CallbackService;
